package deployr.core;

import java.util.*;

public class Pom {

	private boolean insideParent = false;

	private String version = null;

	private boolean scannedDependencies = false;

	private String groupId;

	private String artifactId;

	public Pom(String pom) {
		Scanner scanning = startScanning(pom);
		while (needContinue(scanning)) {
			String line = scanning.next();
			if (openParent(line)) insideParent();
			if (closeParent(line)) notInsideParent();
			if (isGroup(line)) group(line);
			if (isArtifact(line)) artifact(line);
			if (isVersion(line)) version(line);
			if (isDependencies(line)) breakScanning();
		}
	}

	public Artifact artifact() {
		return new Artifact(groupId, artifactId, version);
	}

	private void artifact(String line) {
		artifactId = line.replaceAll(".*<artifactId>", "").replaceAll("</artifactId>.*", "");
	}

	private void breakScanning() {
		scannedDependencies = true;
	}

	private boolean closeParent(String line) {
		return line.contains("</parent>");
	}

	private void group(String line) {
		groupId = line.replaceAll(".*<groupId>", "").replaceAll("</groupId>.*", "");
	}

	private void insideParent() {
		insideParent = true;
	}

	private boolean isArtifact(String line) {
		return line.contains("<artifactId>");
	}

	private boolean isDependencies(String line) {
		return line.contains("<dependencies>");
	}

	private boolean isGroup(String line) {
		return line.contains("<groupId>");
	}

	private boolean isVersion(String line) {
		return line.contains("<version>");
	}

	private boolean needContinue(Scanner scanning) {
		return scanning.hasNext() && !scannedDependencies;
	}

	private void notInsideParent() {
		insideParent = false;
	}

	private boolean openParent(String line) {
		return line.contains("<parent>");
	}

	private Scanner startScanning(String pom) {
		Scanner scanning = new Scanner(pom).useDelimiter("\n");
		return scanning;
	}

	private void version(String line) {
		version = line.replaceAll(".*<version>", "").replaceAll("</version>.*", "");
	}

}
